package com.azzcs.ttl.service;

import com.azzcs.ttl.entity.OrderEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: wzg
 * @Date: 2021/4/13 上午11:48
 */
@Slf4j
@Service
public class OrderService {

    Map<String,OrderEntity> orderMap = new ConcurrentHashMap<>();


    @Autowired
    private AmqpTemplate amqpTemplate;

    public String createOrder(String orderId) {
        OrderEntity orderEntity = orderMap.get(orderId);
        if(orderEntity != null){
            log.info("订单已经存在,orderId: "+orderId);
            return "订单已经存在";
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        OrderEntity order = OrderEntity.builder()
                .orderId(orderId)
                .orderStatus(OrderEntity.OrderStatus.NO_PAY)
                .createTime(timestamp)
                .updateTime(timestamp)
                .build();
        orderMap.put(orderId,order);
        amqpTemplate.convertAndSend("ex.order","rk.order",orderId);
        log.info("下单成功,orderId: "+orderId);
        return "下单成功，请支付";
    }

    public synchronized String payOrder(String orderId) {

        OrderEntity orderEntity = orderMap.get(orderId);
        if(orderEntity == null){
            log.info("订单不存在,orderId: "+orderId);
            return "订单不存在";
        }
        if(orderEntity.getOrderStatus()==OrderEntity.OrderStatus.PAY){
            log.info("订单已支付,orderId: "+orderId);
            return "订单已支付";
        }
        if(orderEntity.getOrderStatus()==OrderEntity.OrderStatus.CANCEL){
            log.info("订单已经过期,orderId: "+orderId);
            return "订单已经过期";
        }
        orderEntity.setOrderStatus(OrderEntity.OrderStatus.PAY);
        log.info("支付成功,orderId: "+orderId);
        return "支付成功";
    }

    public synchronized void cancelOrder(String orderId) {
        OrderEntity orderEntity = orderMap.get(orderId);
        log.info("死信队列执行,orderId: "+orderId);
        if(orderEntity == null){
            return;
        }
        if(orderEntity.getOrderStatus()==OrderEntity.OrderStatus.NO_PAY){
            orderEntity.setOrderStatus(OrderEntity.OrderStatus.CANCEL);
            log.info("订单已过期,orderId: "+orderId);
        }
    }

}
